// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()
const db = cloud.database()

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    var jsonstr = Buffer.from(event.body, 'base64')
    console.log("收到数据，解码base64", jsonstr.toString())
    const strToObj = JSON.parse(jsonstr)
    console.log("解析对象", strToObj)

    const todosCollection = await db.collection('tuya_license').count()
    console.log("授权码文件总数", todosCollection)
    if (todosCollection.total == 0) {
        return {
            'ret': '数据库没有信息'
        }
    }
    var promise = []
    promise.push(db.collection('tuya_license').get())
    var tuya_license = await Promise.all(promise)

    for (let i = 0; i < tuya_license[0].data.length; i++) {
        if (tuya_license[0].data[i].file == strToObj.file) {
            console.log('找到所需文件')
            for (let n = 0; n < tuya_license[0].data[i].license.length; n++) {
                if (tuya_license[0].data[i].license[n].key == strToObj.key && tuya_license[0].data[i].license[n].uuid == strToObj.uuid && tuya_license[0].data[i].license[n].mac == strToObj.mac) {
                    console.log('找到所需操作的授权码')

                    tuya_license[0].data[i].license[n].used = 'lock'
                    promise = []
                    promise.push(db.collection('tuya_license').doc(tuya_license[0].data[i]._id).update({
                        data: {
                            license: tuya_license[0].data[i].license
                        },
                        success: res => {
                            console.log("锁定授权码成功 ", res)
                        },
                        fail: err => {
                            console.log("锁定授权码失败", err)
                        }
                    }))
                    await Promise.all(promise)
                    return {
                        'ret': '操作完毕'
                    }
                }
            }
        }
    }

    return {
        'ret': '找不到所需操作授权码'
    }
}